package xjtu.zd.server.staff.chapter;


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import xjtu.zd.server.common.*;
import xjtu.zd.server.common.page.QueryAction;
import xjtu.zd.server.staff.chapter.impl.ChapterServiceImpl;

import javax.annotation.Resource;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/staff/chapter")
public class ChapterAPI {

    @Resource
    private ChapterServiceImpl chapterService;

    @GetMapping("/search")
    public Result searchChapter(SearchDto dto){
        log.info("访问了接口/staff/chapter/search");
        System.out.println("ch_name:"+dto.getCh_priceh());
        Map<String,Object> page = chapterService.searchChapterPage(dto);
        return Result.success(page);
    }

    @RequestMapping("/handle")//
    public Result chapterHandle(@RequestBody EditDto dto){
        log.info("访问了接口/staff/chapter/handle");
        chapterService.HandleChapter(dto);
        return Result.success();
    }

    @RequestMapping("/getlevel")
    public Result levelMap(){
        log.info("访问了接口/staff/chapter/getlevel");
        return Result.success(chapterService.getLevel());
    }

    @RequestMapping("/getclass")
    public Result classMap(){
        log.info("访问了接口/staff/chapter/getClass");
        return Result.success(chapterService.getClassification());
    }

    @RequestMapping("/getchapter/{ch_id}")//
    public void chapterTxt(@PathVariable String ch_id, HttpServletResponse resp) throws IOException {
        log.info("访问了接口/staff/chapter/getchapter");
        txtChanger changer = new txtChanger();
        ChapterDto dto = chapterService.getChapterfilename(ch_id);
        String filename = CurrentUser.BOOK_DIR+"/"+dto.getB_name()+"/"+dto.getTxt();
        changer.txtToHtml(filename);
        //String[] context = changer.toStringArray(filename);
        //return Result.success(context);

            //读取文件的输入流
        InputStream in = new FileInputStream(filename.substring(0,filename.length()-4)+".html");
            //将文件信息输出到浏览器的输出流
        OutputStream out = resp.getOutputStream();

        byte[] b = new byte[20480];//容量为20480字节的缓存区
        int len = -1;//从输入流读取并放入缓存区的数据量

        while((len=in.read(b))!=-1) {
            out.write(b, 0, len);
        }
        out.flush();
        out.close();
        in.close();
    }
}
